{% extends "base.html" %}

{% block title %}日历计划 - {{ app_name }}{% endblock %}

{% block extra_css %}
<style>
    .calendar-container {
        max-width: 1000px;
        margin: 0 auto;
    }
    .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }
    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 5px;
    }
    .calendar-day-header {
        text-align: center;
        padding: 10px;
        background-color: #f8f9fa;
        font-weight: bold;
    }
    .calendar-day {
        min-height: 100px;
        border: 1px solid #dee2e6;
        padding: 5px;
        position: relative;
    }
    .calendar-day.today {
        background-color: #e6f7ff;
    }
    .calendar-day.other-month {
        background-color: #f8f9fa;
        opacity: 0.5;
    }
    .event {
        background-color: #0d6efd;
        color: white;
        padding: 2px 5px;
        margin-bottom: 3px;
        border-radius: 3px;
        font-size: 12px;
        cursor: pointer;
    }
    .event.reminder {
        background-color: #ffc107;
        color: black;
    }
    .event-add-btn {
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background-color: #0d6efd;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 24px;
        cursor: pointer;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        z-index: 1000;
    }
    .modal {
    tabindex: -1;
    role: dialog;
}
    .modal-dialog {max-width: 500px;}
</style>
{% endblock %}

{% block content %}
<script>
    // 关闭提醒事件
    document.addEventListener('DOMContentLoaded', function() {
        // 关闭提醒按钮点击事件
        document.querySelectorAll('.close-reminder').forEach(button => {
            button.addEventListener('click', function() {
                const eventId = this.getAttribute('data-id');
                if (confirm('确定要关闭此提醒吗？')) {
                    fetch(`/calendar/close_reminder/${eventId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.message) {
                            alert(data.message);
                            // 刷新页面
                            window.location.reload();
                        } else if (data.detail) {
                            alert(data.detail);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('操作失败，请重试');
                    });
                }
            });
        });
    });
</script>
<div class="calendar-container mt-4">
    <div class="calendar-header">
        <h2><i class="fas fa-calendar-alt me-2"></i>日历计划</h2>
        <div class="btn-group">
            <button id="prevMonth" class="btn btn-outline-secondary"><i class="fas fa-chevron-left"></i></button>
            <button id="todayBtn" class="btn btn-secondary">今天</button>
            <button id="nextMonth" class="btn btn-outline-secondary"><i class="fas fa-chevron-right"></i></button>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <h3 id="currentMonth" class="text-center mb-4"></h3>
            <div class="calendar-grid mb-2">
                <div class="calendar-day-header">周日</div>
                <div class="calendar-day-header">周一</div>
                <div class="calendar-day-header">周二</div>
                <div class="calendar-day-header">周三</div>
                <div class="calendar-day-header">周四</div>
                <div class="calendar-day-header">周五</div>
                <div class="calendar-day-header">周六</div>
                <!-- 日历格子将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-list-alt me-2"></i>即将到来的事件</h5>
        </div>
        <div class="card-body">
            <div id="upcomingEvents">
                {% if events %}
                    {% for event in events %}
                        <div class="event-item p-3 border rounded mb-2 {% if event.is_reminder %}border-warning{% endif %}">
                            <div class="d-flex justify-content-between">
                                <h6>{{ event.title }}</h6>
                                <span class="text-muted small">{{ event.event_time.strftime('%Y-%m-%d %H:%M') }}</span>
                            </div>
                            <p class="text-sm text-muted mt-1">{{ event.description }}</p>
                            <div class="d-flex justify-content-end mt-2">
                                <button class="btn btn-sm btn-outline-primary me-2 edit-event" data-id="{{ event.id }}"><i class="fas fa-edit me-1"></i>编辑</button>
                                {% if not event.is_reminder or event.reminder_sent == 1 %}
                                <span class="text-sm text-muted me-2"><i class="fas fa-check-circle me-1"></i>已关闭</span>
                                {% else %}
                                <button class="btn btn-sm btn-outline-warning me-2 close-reminder" data-id="{{ event.id }}"><i class="fas fa-bell-slash me-1"></i>关闭提醒</button>
                                {% endif %}
                                <button class="btn btn-sm btn-outline-danger delete-event" data-id="{{ event.id }}"><i class="fas fa-trash-alt me-1"></i>删除</button>
                            </div>
                        </div>
                    {% endfor %}
                {% else %}
                    <p class="text-muted text-center py-4">暂无事件</p>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 添加事件按钮 -->
<div class="event-add-btn" id="addEventBtn">
    <i class="fas fa-plus"></i>
</div>

<!-- 添加/编辑事件模态框 -->
<div class="modal fade" id="eventModal" tabindex="-1" aria-labelledby="eventModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="eventModalLabel">添加事件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="eventForm">
                <div class="modal-body">
                    <input type="hidden" id="eventId" value="">
                    <div class="mb-3">
                        <label for="eventTitle" class="form-label">事件标题</label>
                        <input type="text" class="form-control" id="eventTitle" required>
                    </div>
                    <div class="mb-3">
                        <label for="eventDescription" class="form-label">事件描述</label>
                        <textarea class="form-control" id="eventDescription" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="eventTime" class="form-label">事件时间</label>
                        <input type="datetime-local" class="form-control" id="eventTime" required>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="isReminder">
                        <label class="form-check-label" for="isReminder">设置提醒</label>
                    </div>
                    <div class="mb-3" id="reminderTimeContainer" style="display: none;">
                        <label for="reminderTime" class="form-label">提醒时间</label>
                        <div class="d-flex flex-column gap-2">
                            <input type="datetime-local" class="form-control" id="reminderTime">
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-sm btn-outline-secondary set-reminder-time" data-minutes="5">提前5分钟</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary set-reminder-time" data-minutes="10">提前10分钟</button>
                                <button type="button" class="btn btn-sm btn-outline-primary set-reminder-time" data-minutes="30">提前30分钟</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除此事件吗？此操作不可撤销。</p>
                <input type="hidden" id="deleteEventId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 初始化日历
    document.addEventListener('DOMContentLoaded', function() {
        // 设置当前年月
        const today = new Date();
        let currentMonth = today.getMonth();
        let currentYear = today.getFullYear();
        
        // 渲染日历
        renderCalendar(currentMonth, currentYear);
        updateCurrentMonthDisplay(currentMonth, currentYear);
        
        // 绑定按钮事件
        document.getElementById('prevMonth').addEventListener('click', function() {
            currentMonth--;
            if (currentMonth < 0) {
                currentMonth = 11;
                currentYear--;
            }
            renderCalendar(currentMonth, currentYear);
            updateCurrentMonthDisplay(currentMonth, currentYear);
        });
        
        document.getElementById('nextMonth').addEventListener('click', function() {
            currentMonth++;
            if (currentMonth > 11) {
                currentMonth = 0;
                currentYear++;
            }
            renderCalendar(currentMonth, currentYear);
            updateCurrentMonthDisplay(currentMonth, currentYear);
        });
        
        document.getElementById('todayBtn').addEventListener('click', function() {
            currentMonth = today.getMonth();
            currentYear = today.getFullYear();
            renderCalendar(currentMonth, currentYear);
            updateCurrentMonthDisplay(currentMonth, currentYear);
        });
        
        // 提醒复选框事件
        document.getElementById('isReminder').addEventListener('change', function() {
            const reminderContainer = document.getElementById('reminderTimeContainer');
            if (this.checked) {
                reminderContainer.style.display = 'block';
                // 默认选择提前30分钟
                document.querySelector('.set-reminder-time[data-minutes="30"]').click();
            } else {
                reminderContainer.style.display = 'none';
            }
        });

        // 提醒时间预设按钮事件
        document.querySelectorAll('.set-reminder-time').forEach(button => {
            button.addEventListener('click', function() {
                const eventTimeInput = document.getElementById('eventTime');
                const reminderTimeInput = document.getElementById('reminderTime');
                const minutes = parseInt(this.getAttribute('data-minutes'));

                if (eventTimeInput.value) {
                    const eventTime = new Date(eventTimeInput.value);
                    const reminderTime = new Date(eventTime);
                    reminderTime.setMinutes(reminderTime.getMinutes() - minutes);

                    // 格式化提醒时间
                    const year = reminderTime.getFullYear();
                    const month = String(reminderTime.getMonth() + 1).padStart(2, '0');
                    const day = String(reminderTime.getDate()).padStart(2, '0');
                    const hours = String(reminderTime.getHours()).padStart(2, '0');
                    const mins = String(reminderTime.getMinutes()).padStart(2, '0');
                    const formattedReminderTime = `${year}-${month}-${day}T${hours}:${mins}`;

                    reminderTimeInput.value = formattedReminderTime;

                    // 更新按钮样式
                    document.querySelectorAll('.set-reminder-time').forEach(btn => {
                        btn.classList.remove('btn-outline-primary');
                        btn.classList.add('btn-outline-secondary');
                    });
                    this.classList.remove('btn-outline-secondary');
                    this.classList.add('btn-outline-primary');
                }
            });
        });
        
        // 添加事件按钮
        document.getElementById('addEventBtn').addEventListener('click', function() {
            document.getElementById('eventModalLabel').textContent = '添加事件';
            document.getElementById('eventId').value = '';
            document.getElementById('eventForm').reset();
            
            // 设置默认事件时间为当前时间
            const now = new Date();
            
            // 确保使用本地时间而非UTC时间
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const formattedDate = `${year}-${month}-${day}T${hours}:${minutes}`;
            
            document.getElementById('eventTime').value = formattedDate;
            
            // 默认不勾选提醒
            document.getElementById('isReminder').checked = false;
            document.getElementById('reminderTimeContainer').style.display = 'none';
            
            // 默认提醒时间为事件时间前30分钟
            const reminderTime = new Date(now);
            reminderTime.setMinutes(reminderTime.getMinutes() - 30);
            const reminderYear = reminderTime.getFullYear();
            const reminderMonth = String(reminderTime.getMonth() + 1).padStart(2, '0');
            const reminderDay = String(reminderTime.getDate()).padStart(2, '0');
            const reminderHours = String(reminderTime.getHours()).padStart(2, '0');
            const reminderMinutes = String(reminderTime.getMinutes()).padStart(2, '0');
            const formattedReminderDate = `${reminderYear}-${reminderMonth}-${reminderDay}T${reminderHours}:${reminderMinutes}`;
            
            document.getElementById('reminderTime').value = formattedReminderDate;
            
            new bootstrap.Modal(document.getElementById('eventModal')).show();
        });
        
        // 事件表单提交
            document.getElementById('eventForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                const eventId = document.getElementById('eventId').value;
                const title = document.getElementById('eventTitle').value;
                const description = document.getElementById('eventDescription').value;
                const eventTime = document.getElementById('eventTime').value;
                const isReminder = document.getElementById('isReminder').checked;
                const reminderTime = isReminder ? document.getElementById('reminderTime').value : '';
                
                // 构建表单数据
                const formData = new FormData();
                formData.append('title', title);
                formData.append('description', description);
                formData.append('event_time', eventTime);
                formData.append('is_reminder', isReminder ? 'true' : 'false');
                formData.append('reminder_time', reminderTime);
                
                // 调试信息
                console.log('提交is_reminder值:', isReminder ? 'true' : 'false');
                console.log('复选框状态:', document.getElementById('isReminder').checked);
            
            // 发送请求
            let url = '/calendar/add';
            if (eventId) {
                url = `/calendar/edit/${eventId}`;
            }
            
            fetch(url, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.message) {
                    alert(data.message);
                    location.reload(); // 刷新页面
                } else if (data.detail) {
                    alert(data.detail);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
        });
        
        // 编辑事件按钮
        document.querySelectorAll('.edit-event').forEach(button => {
            button.addEventListener('click', function() {
                const eventId = this.getAttribute('data-id');
                
                // 获取事件详情
                fetch(`/calendar/events/${eventId}`)
                .then(response => response.json())
                .then(event => {
                    if (event) {
                        document.getElementById('eventModalLabel').textContent = '编辑事件';
                        document.getElementById('eventId').value = event.id;
                        document.getElementById('eventTitle').value = event.title;
                        document.getElementById('eventDescription').value = event.description;
                        document.getElementById('eventTime').value = event.event_time;
                        // 设置提醒复选框状态
                        const isReminderCheckbox = document.getElementById('isReminder');
                        isReminderCheckbox.checked = event.is_reminder;
                        
                        // 更新提醒时间容器显示状态
                        if (event.is_reminder) {
                            document.getElementById('reminderTimeContainer').style.display = 'block';
                            document.getElementById('reminderTime').value = event.reminder_time;
                        } else {
                            document.getElementById('reminderTimeContainer').style.display = 'none';
                        }

                        // 为复选框添加状态变化监听
                        isReminderCheckbox.onchange = function() {
                            if (this.checked) {
                                document.getElementById('reminderTimeContainer').style.display = 'block';
                            } else {
                                document.getElementById('reminderTimeContainer').style.display = 'none';
                            }
                        };
                        
                        new bootstrap.Modal(document.getElementById('eventModal')).show();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取事件详情失败');
                });
            });
        });
        
        // 删除事件按钮
        document.querySelectorAll('.delete-event').forEach(button => {
            button.addEventListener('click', function() {
                const eventId = this.getAttribute('data-id');
                document.getElementById('deleteEventId').value = eventId;
                new bootstrap.Modal(document.getElementById('deleteModal')).show();
            });
        });
        
        // 确认删除按钮
        document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
            const eventId = document.getElementById('deleteEventId').value;
            
            fetch(`/calendar/delete/${eventId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.message) {
                    alert(data.message);
                    location.reload(); // 刷新页面
                } else if (data.detail) {
                    alert(data.detail);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败，请重试');
            });
        });
        
        // 测试提醒按钮
        document.querySelectorAll('.test-reminder').forEach(button => {
            button.addEventListener('click', function() {
                const eventId = this.getAttribute('data-id');
                if (confirm('确定要发送测试提醒吗？')) {
                    fetch(`/calendar/test_reminder/${eventId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.message) {
                            alert(data.message);
                        } else if (data.detail) {
                            alert(data.detail);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('发送测试提醒失败，请重试');
                    });
                }
            });
        });
    });
    
    // 渲染日历
    function renderCalendar(month, year) {
        const calendarGrid = document.querySelector('.calendar-grid');
        // 清空日历格子，但保留表头
        const dayHeaders = document.querySelectorAll('.calendar-day-header');
        calendarGrid.innerHTML = '';
        dayHeaders.forEach(header => calendarGrid.appendChild(header));
        
        // 获取当月第一天是星期几
        const firstDay = new Date(year, month, 1).getDay();
        // 获取当月的天数
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        // 获取上个月的天数
        const daysInPrevMonth = new Date(year, month, 0).getDate();
        
        // 添加上个月的尾巴
        for (let i = firstDay; i > 0; i--) {
            const day = document.createElement('div');
            day.className = 'calendar-day other-month';
            day.innerHTML = `<div class="day-number">${daysInPrevMonth - i + 1}</div>`;
            calendarGrid.appendChild(day);
        }
        
        // 添加当月的天数
        const today = new Date();
        for (let i = 1; i <= daysInMonth; i++) {
            const day = document.createElement('div');
            day.className = 'calendar-day';
            
            // 如果是今天，添加today类
            if (i === today.getDate() && month === today.getMonth() && year === today.getFullYear()) {
                day.classList.add('today');
            }
            
            day.innerHTML = `<div class="day-number">${i}</div>`;
            // 添加点击事件
            day.addEventListener('click', function() {
                // 使用点击的日期和当前时间作为默认值
                const now = new Date();
                const clickedDate = new Date(year, month, i);
                
                // 确保使用本地时间而非UTC时间
                const eventYear = clickedDate.getFullYear();
                const eventMonth = String(clickedDate.getMonth() + 1).padStart(2, '0');
                const eventDay = String(clickedDate.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                const formattedDate = `${eventYear}-${eventMonth}-${eventDay}T${hours}:${minutes}`;
                
                document.getElementById('eventModalLabel').textContent = '添加事件';
                document.getElementById('eventId').value = '';
                
                // 先重置表单
                document.getElementById('eventForm').reset();
                
                // 立即设置默认值
                document.getElementById('eventTime').value = formattedDate;
                document.getElementById('isReminder').checked = false;
                document.getElementById('reminderTimeContainer').style.display = 'none';
                
                // 默认提醒时间为事件时间前30分钟
                const reminderTime = new Date(clickedDate);
                reminderTime.setHours(now.getHours());
                reminderTime.setMinutes(now.getMinutes() - 30);
                const reminderYear = reminderTime.getFullYear();
                const reminderMonth = String(reminderTime.getMonth() + 1).padStart(2, '0');
                const reminderDay = String(reminderTime.getDate()).padStart(2, '0');
                const reminderHours = String(reminderTime.getHours()).padStart(2, '0');
                const reminderMinutes = String(reminderTime.getMinutes()).padStart(2, '0');
                const formattedReminderDate = `${reminderYear}-${reminderMonth}-${reminderDay}T${reminderHours}:${reminderMinutes}`;
                
                document.getElementById('reminderTime').value = formattedReminderDate;
                
                new bootstrap.Modal(document.getElementById('eventModal')).show();
            });
            calendarGrid.appendChild(day);
        }
        
        // 添加下个月的头部，使日历保持7列
        const totalDays = firstDay + daysInMonth;
        const nextMonthDays = 7 - (totalDays % 7) || 7;
        if (totalDays % 7 !== 0) {
            for (let i = 1; i <= nextMonthDays; i++) {
                const day = document.createElement('div');
                day.className = 'calendar-day other-month';
                day.innerHTML = `<div class="day-number">${i}</div>`;
                calendarGrid.appendChild(day);
            }
        }
    }
    
    // 更新当前年月显示
    function updateCurrentMonthDisplay(month, year) {
        const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
        document.getElementById('currentMonth').textContent = `${year}年 ${monthNames[month]}`;
    }
</script>
{% endblock %}